package com.onec.service.manage.config;

import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.connection.ReturnType;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.types.Expiration;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;


/**
 * redis 默认锁的操作
 */
@Component
public class RedisLockUtil {


    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    //加锁
    public Boolean getLock(final String key, final String requestId, final long expirationTime, final TimeUnit timeUnit) {
        return redisTemplate.execute((RedisCallback<Boolean>) connection -> connection.set(key.getBytes(), (requestId == null ? "" : requestId).getBytes(),
                Expiration.from(expirationTime, timeUnit),
                RedisStringCommands.SetOption.ifAbsent()));
    }

    //释放锁
    public Boolean releaseLock(String key, String requestId) {
        return redisTemplate.execute((RedisCallback<Boolean>) connection -> {
            String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
            return connection.eval(script.getBytes(), ReturnType.BOOLEAN, 1, key.getBytes(), requestId.getBytes());
        });
    }

}
